package com.lau.controller;

import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson2.JSONObject;
import com.lau.entity.TSysFile;
import com.lau.service.ITSysFileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @author:Lau
 * @create: 2024-06-07 16:36
 * @Description: 文件上传
 */
@RestController
@Slf4j
public class UploadController {

    @Autowired
    ITSysFileService fileService;

    @PostMapping("/upload")
    public JSONObject upload(MultipartFile file) {
        return fileService.upload(file);
    }

    /**
     * 文件下载
     *
     * @param fileId   fileId
     * @param response 响应
     */
    @GetMapping(value = "/download/{fileId}")
    public void download(@PathVariable String fileId, HttpServletResponse response) {
        OutputStream outputStream = null;
        TSysFile fileInfo = fileService.getById(fileId);
        if (fileInfo == null) {
            throw new RuntimeException("文件不存在");
        }
        try {
            response.reset();
            response.setContentType("application/octet-stream; charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileInfo.getFileName());
            // 获取输出流
            outputStream = response.getOutputStream();
            FileUtil.writeToStream(fileInfo.getFilePath(), outputStream);
        } catch (IOException e) {
            log.error("文件下载出错:{}", e.getMessage());
        } finally {
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                log.error("关闭流时出错:{}", e.getMessage());
            }
        }
    }

    /**
     * 图片/PDF查看
     *
     * @param fileId fileId
     * @return {@link ResponseEntity}<{@link byte[]}>
     */
    @GetMapping(value = "/view/{fileId}")
    public ResponseEntity<byte[]> viewFilesImage(@PathVariable String fileId){
        TSysFile fileInfo = fileService.getById(fileId);
        if (fileInfo == null) {
            throw new RuntimeException("文件不存在");
        }
        byte[] bytes = FileUtil.readBytes(fileInfo.getFilePath());
        return ResponseEntity.ok().contentType(MediaType.APPLICATION_PDF).body(bytes);
    }
}
